import React, { forwardRef, useEffect, useState } from 'react'
import { Form, Input, Select } from 'antd'
const { Option } = Select;

const UserFrom = forwardRef((props, ref) => {
  const [isDisable, setisDisable] = useState(false)
  const { roleId, region } = JSON.parse(localStorage.getItem('token'))
  useEffect(() => {
    setisDisable(props.isUpdateDisable)
  }, [props.isUpdateDisable])
  const roleIdChange = value => {
    if (value === 1) {
      ref.current.setFieldsValue({
        region: ''
      })
      setisDisable(true)
    } else {
      setisDisable(false)
    }
  }
  const checkRegionDisabled = item => {
    if (props.isUpdate) {
      if (roleId === 1) {
        return false
      } else {
        return true
      }
    } else {
      if (roleId === 1) {
        return false
      } else {
        return item.value!==region
      }
    }
  }
  const checkRoleDisabled = item => {
    if (props.isUpdate) {
      if (roleId === 1) {
        return false
      } else {
        return true
      }
    } else {
      if (roleId === 1) {
        return false
      } else {
        return item.id!==3
      }
    }
  }

  return (
    <Form
      ref={ref}
      layout="vertical"
    >
      <Form.Item
        name="username"
        label="用户名"
        rules={[
          {
            required: true,
            message: '请输入用户名',
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="password"
        label="密码"
        rules={[
          {
            required: true,
            message: '请输入密码',
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="region"
        label="区域"
        rules={isDisable?[]:[{required: true,message: '请选择区域',}]}
      >
        <Select disabled={isDisable}>
          {
            props.regionList.map(item => {
              return <Option key={item.id} disabled={checkRegionDisabled(item)} value={item.value}>{item.title}</Option>
            })
          }
        </Select>
      </Form.Item>
      <Form.Item
        name="roleId"
        label="角色名称"
        rules={[
          {
            required: true,
            message: '请选择角色名称',
          },
        ]}
      >
        <Select
          onChange={roleIdChange}
        >
          {
            props.roleList.map(item => {
              return <Option key={item.id} disabled={checkRoleDisabled(item)} value={item.id}>{item.roleName}</Option>
            })
          }
        </Select>
      </Form.Item>
    </Form>
  )
})

export default UserFrom